package com.hzjh.service.metamask

import com.blankj.utilcode.util.AppUtils
import com.hzjh.base.ext.R
import com.hzjh.base.ext.utils.AppUpdateUtils
import com.hzjh.base.log.JHLogger
import com.hzjh.base.style.view.dialog.ConfirmDialog
import com.hzjh.base.utils.other.ActivityStackManage
import com.hzjh.base.utils.other.CommUtils
import io.metamask.androidsdk.DappMetadata
import io.metamask.androidsdk.Ethereum
import io.metamask.androidsdk.EthereumMethod
import io.metamask.androidsdk.EthereumRequest
import io.metamask.androidsdk.Result
import java.math.BigInteger
import kotlin.math.pow

class MetaMaskUtils {
    private lateinit var dapp : DappMetadata
    private val ethereum by lazy { Ethereum(ActivityStackManage.currentActivity(),dapp) }
    private var ifConnected = false //是否连接

    companion object{
        private var metaMaskUtils: MetaMaskUtils? = null
        fun init(name:String,url:String,iconUrl:String?="https://hzjh.s3.amazonaws.com/crmebimage/public/maintain/2024/01/26/310f6b2147cb4b80beb9c39d39237ba5hz5t6y33mp.png"){
            if(metaMaskUtils==null) {
                metaMaskUtils = MetaMaskUtils()
                metaMaskUtils?.dapp = DappMetadata(name, url, iconUrl)
            }
            //每次初始化需要重新链接
//            metaMaskUtils?.ifConnected=false
        }
        fun getInstance(): MetaMaskUtils?{
            return metaMaskUtils
        }
    }

    fun reqConnect(callBack: ((address: String) -> Unit)?=null) {
        if(ifConnected){
            JHLogger.d("Connected already address--- ${ethereum.selectedAddress}")
            callBack?.invoke(ethereum.selectedAddress)
            return
        }
        if(!isMetaMaskAppInstall()){
            //未安装MetaMask
            ConfirmDialog.Builder(ActivityStackManage.currentActivity())
                .setMessage(CommUtils.getString(R.string.jh_no_metamask_tip))
                .setCancelButton(CommUtils.getString(R.string.jh_cancel)){ dialog, _ ->
                    dialog.dismiss()
                }.setSureButton(CommUtils.getString(R.string.jh_install)) { dialog, _ ->
                    startMetaMaskGooglePlay()
                    dialog.dismiss()
                }.setCanCancel(true).create().show()
            return
        }

        ethereum.connect { result ->
            when (result) {
                is Result.Error -> {
                    ifConnected=false
                    JHLogger.e("Ethereum connection error: ${result.error.message}")
                }
                is Result.Success -> {
                    ifConnected=true
                    callBack?.invoke(ethereum.selectedAddress)
                    JHLogger.d("Ethereum connection result: $result")
                }
            }
        }
    }
    // Wrapper function call all RPC methods
    private fun sendRequest(success: ((Result.Success) -> Unit)?=null,error: ((Result.Error) -> Unit)?=null,request: (() -> EthereumRequest)) {
        reqConnect {
            ethereum.sendRequest(request()) { result ->
                when (result) {
                    is Result.Error -> {
                        JHLogger.e("sendRequest error: ${result.error.message}")
                        error?.invoke(result)
                    }

                    is Result.Success -> {
                        JHLogger.d("sendRequest result: $result")
                        success?.invoke(result)
                    }
                }
            }
        }
    }

    /**
     * 获取余额 没有获取成功
     * Ethereum API
     */
    fun reqGetBalance() {
        // Make request
        sendRequest {
            // Create parameters
            val params: List<String> = listOf(
                ethereum.selectedAddress,
                "latest"
            )
            // Create request
            EthereumRequest(
                method = EthereumMethod.ETH_GET_BALANCE.value,
                params = params
            )
        }
    }
    /**
     * 发送交易
     */
    fun reqSendTransaction(to:String,amount:String,
                           success:((payNo:String) -> Unit)?=null,
                           fail:(() -> Unit)?=null) {
        JHLogger.d("发送交易---to:$to")
        JHLogger.d("发送交易---amount:$amount")
        // Make request
        sendRequest(
            request = {
                val params: Map<String, Any> = mapOf(
                    "from" to ethereum.selectedAddress,
                    "to" to to,
                    "value" to amount,
                )
                // Create request
                EthereumRequest(
                    method = EthereumMethod.ETH_SEND_TRANSACTION.value,
                    params = listOf(params)
                )
            },
            success = {
                JHLogger.d("sendRequest success: $it")
                when(it){
                    is Result.Success.Item->{
                        //正常的交易成功
                        success?.invoke(it.value)
                    }
                    else -> {
                        success?.invoke(it.toString())
                    }
                }
            },
            error = {
                fail?.invoke()
            }
        )

    }

    //字符串转16进制
    fun changeMoneyToHex(money:String,ethRate:String?):String{
        //修改汇率
        return ethRate?.let {
            val longValue = (money.toFloat() / it.toFloat() * 10.0.pow(18.0)).toBigDecimal().toBigInteger()
            JHLogger.d("changeMoneyToHex-----$longValue")
            longToHex(longValue)
        }?:""
    }

    //16进制转字符串
    private fun longToHex(longValue: BigInteger): String {
        return longValue.toString(16)
    }

    private fun startMetaMaskGooglePlay() {
        AppUpdateUtils.startGooglePlay("io.metamask")
    }
    /**
     * 检测MetaMask是否安装
     */
    private fun isMetaMaskAppInstall(): Boolean {
        return AppUtils.isAppInstalled("io.metamask")
    }
}